<template>
  <div class="profile-container">
    <div v-if="isLoggedIn">
      <div class="user-info">
        <div 
          class="avatar" 
          :style="{ backgroundColor: currentUser.avatarColor }" 
          @click="toggleAvatarOptions"
        >
          <!-- 使用背景色代替图片 -->
        </div>
        <h2>{{ currentUser.username }}</h2>
        <p>{{ currentUser.email }}</p>
      </div>

      <!-- 头像颜色选择弹窗 -->
      <div v-if="showAvatarOptions" class="avatar-modal" @click="toggleAvatarOptions">
        <div class="modal-content" @click.stop>
          <h3>选择头像颜色</h3>
          <div class="avatar-grid">
            <div 
              class="color-option" 
              v-for="color in avatarColors" 
              :key="color" 
              :style="{ backgroundColor: color }" 
              @click="changeAvatarColor(color)"
            ></div>
          </div>
          <input type="color" v-model="customColor" @input="changeAvatarColor(customColor)" />
          <button @click="toggleAvatarOptions" class="close-btn">关闭</button>
        </div>
      </div>

      <div class="account-info">
        <div class="info-item">
          <h3>零食余额</h3>
          <p>¥{{ currentUser.balance.toFixed(2) }}</p>
        </div>
        <div class="info-item">
          <h3>美味积分</h3>
          <p>{{ currentUser.points }} 分</p>
        </div>
      </div>
      <div class="user-actions">
        <button @click="showCoupons = !showCoupons" class="action-btn">我的优惠券 ({{ currentUser.coupons.length }})</button>
        <button @click="showFavorites = !showFavorites" class="action-btn">我的收藏 ({{ currentUser.favorites.length }})</button>
        <button @click="toggleRechargeOptions" class="action-btn">充值</button>
        <button @click="editProfile" class="action-btn">编辑个人资料</button>
        <button @click="viewOrderHistory" class="action-btn">查看订单历史</button>
        <button @click="toggleAddressManagement" class="action-btn">管理收货地址</button>
        <button @click="logout" class="logout-btn">退出登录</button>
      </div>

      <!-- 弹窗 -->
      <div v-if="showRechargeOptions" class="recharge-modal">
        <div class="modal-content">
          <h3>选择充值金额</h3>
          <div class="recharge-grid">
            <div class="recharge-card" v-for="amount in rechargeAmounts" :key="amount" @click="recharge(amount)">
              <p>¥{{ amount }}</p>
            </div>
          </div>
          <div class="custom-recharge">
            <input type="number" v-model="customAmount" placeholder="自定义金额" min="10" />
            <button @click="recharge(customAmount)" class="action-btn">充值</button>
            <p class="note">最低充值10元起</p>
          </div>
          <button @click="toggleRechargeOptions" class="close-btn">关闭</button>
        </div>
      </div>

      <div v-if="showCoupons" class="coupons">
        <h3>我的优惠券</h3>
        <ul>
          <li v-for="coupon in currentUser.coupons" :key="coupon.id" class="coupon-item">
            <span class="coupon-name">{{ coupon.name }}</span>
            <span class="coupon-value">满{{ coupon.threshold }}减{{ coupon.discount }}</span>
            <span class="coupon-expiry">有效期至：{{ coupon.expiryDate }}</span>
          </li>
        </ul>
      </div>
      <div v-if="showFavorites" class="favorites">
        <h3>我的收藏</h3>
        <ul>
          <li v-for="item in currentUser.favorites" :key="item.id" class="favorite-item">
            <span class="favorite-name">{{ item.name }}</span>
            <span class="favorite-price">¥{{ item.price.toFixed(2) }}</span>
            <button @click="addToCart(item)" class="add-to-cart-btn">加入购物车</button>
          </li>
        </ul>
      </div>
      <div v-if="isAddressManagementVisible" class="address-management">
        <h3>管理收货地址</h3>
        <p>当前地址: {{ currentAddress }}</p>
        <input v-model="newAddress" placeholder="输入新地址" />
        <button @click="updateAddress">修改地址</button>
      </div>
    </div>
    <div v-else class="login-register">
      <h2>欢迎来到零食天地</h2>
      <p>请登录或注册以享受更多美味体验</p>
      <div class="auth-buttons">
        <button @click="goToLogin" class="login-btn">登录</button>
        <button @click="goToRegister" class="register-btn">注册</button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useCartStore } from '../stores/cartStore';

export default {
  name: 'Profile',
  setup() {
    const router = useRouter();
    const cartStore = useCartStore();
    const isLoggedIn = ref(false);
    const showCoupons = ref(false);
    const showFavorites = ref(false);
    const isAddressManagementVisible = ref(false);
    const showRechargeOptions = ref(false);
    const showAvatarOptions = ref(false); // 控制头像选择的显示
    const currentUser = ref({
      username: '蔡徐坤',
      email: 'ikun@example.com',
      avatar: '/images/avatar.jpg',
      avatarColor: 'red', // 默认头像颜色
      balance: 0,
      points: 1500,
      coupons: [
        { id: 1, name: '新人优惠', threshold: 50, discount: 10, expiryDate: '2023-12-31' },
        { id: 2, name: '周年庆优惠', threshold: 100, discount: 20, expiryDate: '2023-11-30' },
      ],
      favorites: [
        { id: 1, name: '雷碧', price: 9.99 },
        { id: 2, name: '六个核弹', price: 9.99 },
      ],
    });
    const currentAddress = ref('');
    const newAddress = ref('');
    const rechargeAmounts = [10, 50, 100, 200, 300];
    const customAmount = ref(10); // 自定义金额，默认10元
    const avatarColors = ['red', 'green', 'blue']; // 头像颜色选项
    const customColor = ref(''); // 自定义颜色

    onMounted(() => {
      const token = localStorage.getItem('token');
      isLoggedIn.value = !!token;
      currentAddress.value = localStorage.getItem('currentAddress') || '123 假街, 假城市';
      currentUser.value.balance = parseFloat(localStorage.getItem('balance')) || 0;
      currentUser.value.avatarColor = localStorage.getItem('avatarColor') || 'red'; // 从 localStorage 中读取头像颜色
    });

    const toggleRechargeOptions = () => {
      showRechargeOptions.value = !showRechargeOptions.value;
    };

    const toggleAddressManagement = () => {
      isAddressManagementVisible.value = !isAddressManagementVisible.value;
    };

    const toggleAvatarOptions = () => {
      showAvatarOptions.value = !showAvatarOptions.value; // 切换头像选择的显示状态
    };

    const changeAvatarColor = (color) => {
      currentUser.value.avatarColor = color; // 更新头像颜色
      localStorage.setItem('avatarColor', color); // 保存到 localStorage
    };

    const logout = () => {
      localStorage.removeItem('token');
      isLoggedIn.value = false;
      cartStore.$reset();
      router.push('/login');
    };

    const goToLogin = () => {
      router.push('/login');
    };

    const goToRegister = () => {
      router.push('/register');
    };

    const recharge = (amount) => {
      if (amount < 10) {
        alert('最低充值金额为10元！');
        return;
      }
      alert(`充值成功！充值金额: ¥${amount}`);
      currentUser.value.balance += amount;
      localStorage.setItem('balance', currentUser.value.balance); // 更新 localStorage 中的余额
      alert(`当前余额: ¥${currentUser.value.balance.toFixed(2)}`);
      showRechargeOptions.value = false;
    };

    const editProfile = () => {
      alert('编辑个人资料');
    };

    const viewOrderHistory = () => {
      router.push('/Order/Order');
    };

    const addToCart = (item) => {
      cartStore.addToCart(item);
      alert('商品已添加到购物车！');
    };

    const updateAddress = () => {
      if (newAddress.value) {
        currentAddress.value = newAddress.value;
        localStorage.setItem('currentAddress', newAddress.value);
        newAddress.value = '';
        alert('地址已更新！');
      } else {
        alert('请输入新地址！');
      }
    };

    return {
      isLoggedIn,
      currentUser,
      showCoupons,
      showFavorites,
      isAddressManagementVisible,
      showRechargeOptions,
      customAmount,
      avatarColors,
      showAvatarOptions,
      toggleRechargeOptions,
      toggleAddressManagement,
      toggleAvatarOptions,
      changeAvatarColor,
      logout,
      goToLogin,
      goToRegister,
      recharge,
      editProfile,
      viewOrderHistory,
      addToCart,
      currentAddress,
      newAddress,
      updateAddress,
      rechargeAmounts,
    };
  },
};
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #FFF3E0;
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
.user-info {
  text-align: center;
  margin-bottom: 20px;
  display: flex;
  flex-direction: column; /* 垂直排列 */
  align-items: center; /* 水平居中 */
}
.avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: red; /* 使用背景色代替图片 */
  cursor: pointer; /* 鼠标悬停时显示为可点击 */
}
h2 {
  color: #FF6F00;
  margin: 10px 0 5px;
}
.account-info {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
  background-color: white;
  padding: 15px;
  border-radius: 8px;
}
.info-item {
  text-align: center;
}
.info-item h3 {
  color: #FF6F00;
  margin-bottom: 5px;
}
.user-actions {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
  margin-bottom: 20px;
}
.action-btn, .logout-btn {
  padding: 10px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.action-btn {
  background-color: #FFB74D;
  color: white;
}
.logout-btn {
  background-color: #FF6F00;
  color: white;
}
.action-btn:hover, .logout-btn:hover {
  opacity: 0.8;
}

/* 头像颜色选择样式 */
.avatar-options {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
.color-option {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin: 0 5px;
  cursor: pointer;
  border: 2px solid transparent;
}
.color-option:hover {
  border: 2px solid #FF6F00; /* 鼠标悬停时显示边框 */
}

/* 弹窗样式 */
.recharge-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  text-align: center;
}
.recharge-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  margin: 20px 0;
}
.recharge-card {
  padding: 15px;
  background-color: #FFB74D;
  color: white;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s;
}
.recharge-card:hover {
  background-color: #FF6F00;
}
.custom-recharge {
  margin-top: 20px;
}
.custom-recharge input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  width: 100px;
}
.coupons, .favorites {
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  margin-top: 20px;
}
.coupon-item, .favorite-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #FFF3E0;
  margin-bottom: 10px;
  border-radius: 5px;
}
.add-to-cart-btn {
  background-color: #FF6F00;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 3px;
  cursor: pointer;
}
.login-register {
  text-align: center;
}
.auth-buttons {
  margin-top: 20px;
}
.login-btn, .register-btn {
  padding: 10px 20px;
  margin: 0 10px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s;
}
.login-btn {
  background-color: #FF6F00;
  color: white;
}
.register-btn {
  background-color: #FFB74D;
  color: white;
}
.login-btn:hover, .register-btn:hover {
  opacity: 0.8;
}
.address-management {
  margin-top: 20px;
  padding: 15px;
  background-color: white;
  border-radius: 8px;
}
.close-btn {
  margin-top: 10px;
  padding: 10px;
  background-color: #FF6F00;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.close-btn:hover {
  opacity: 0.8;
}
.note {
  margin-top: 5px;
  font-size: 12px;
  color: #888;
}
.avatar-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.avatar-grid {
  display: flex;
  justify-content: center;
  margin: 20px 0;
}
</style>
